<template>
	<view class="bindingcode-page">
		<view class="hintcode">短信验证码已经发送到<br>{{ maskPhone }}</view>
		
		<view class="bindingcode-item">
			<input 
                type="text" 
                placeholder="请输入验证码" 
                class="bindingcode-input"
                v-model="verificationCode"
                maxlength="6"
            />
			<text 
                :class="['code', { 'disabled': isCounting }]" 
                :disabled="isCounting" 
                @click="startCountdown"
            >
                {{ countdownText }}
            </text>
			<button 
                type="default" 
                class="bindingcode-btn"
                @click="submitCode"
            >
                提交
            </button>
		</view>
	</view>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';

const verificationCode = ref('');
const isCounting = ref(false);
const secondsRemaining = ref(60);
const countdownText = ref('获取验证码');
const phone = ref('');

// 计算属性：手机号掩码显示
const maskPhone = computed(() => {
    if (!phone.value) return '';
    return phone.value.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
});

onMounted(() => {
    // 从本地存储获取手机号
    phone.value = uni.getStorageSync('phone') || '';
});

// 开始倒计时
const startCountdown = async () => {
    if (isCounting.value) return;

    try {
        const res = await uni.request({
            method: 'POST',
            url: 'http://localhost:9100/api/user/sendVerificationCode',
            header: {
                'bece_token': uni.getStorageSync('bece_token')
            },
            data: {
                phone: phone.value
            }
        });

        if (res.data.code === 200) {
            // 开始倒计时
            isCounting.value = true;
            const timer = setInterval(() => {
                secondsRemaining.value -= 1;
                countdownText.value = `${secondsRemaining.value}s后重新获取`;

                if (secondsRemaining.value <= 0) {
                    clearInterval(timer);
                    resetCountdown();
                }
            }, 1000);
        } else {
            uni.showToast({
                title: res.data.msg || '发送验证码失败',
                icon: 'none',
                duration: 2000
            });
        }
    } catch (err) {
        uni.showToast({
            title: '网络请求失败，请稍后重试',
            icon: 'none',
            duration: 2000
        });
        console.error('发送验证码请求出错:', err);
    }
};

// 重置倒计时
const resetCountdown = () => {
    isCounting.value = false;
    secondsRemaining.value = 60;
    countdownText.value = '重新获取';
};

// 提交验证码
const submitCode = async () => {
    if (!verificationCode.value || verificationCode.value.length !== 4) {
        uni.showToast({
            title: '请输入4位验证码',
            icon: 'none',
            duration: 2000
        });
        return;
    }

    try {
        const userId = uni.getStorageSync('userId');
        const res = await uni.request({
            method: 'POST',
            url: 'http://localhost:9100/api/user/updatePhone',
            header: {
                'bece_token': uni.getStorageSync('bece_token')
            },
            data: {
                id: userId,
                phone: phone.value,
                code: verificationCode.value
            }
        });

        if (res.data.code === 200) {
            uni.showToast({
                title: '手机号绑定成功',
                icon: 'success',
                duration: 2000
            });
            
            // 清除本地存储的临时手机号
            uni.removeStorageSync('phone');
            
            // 跳转到指定页面
            setTimeout(() => {
                uni.navigateTo({
                    url: '/pages/setting/setting/setting' 
                });
            }, 2000);
        } else {
            uni.showToast({
                title: res.data.msg || '验证码验证失败',
                icon: 'none',
                duration: 2000
            });
        }
    } catch (err) {
        uni.showToast({
            title: '网络请求失败，请稍后重试',
            icon: 'none',
            duration: 2000
        });
        console.error('验证码验证请求出错:', err);
    }
};
</script>

<style scoped>
.bindingcode-page {
    padding: 40rpx 60rpx;
}

.hintcode {
    margin: 50rpx;
    font-size: 40rpx;
    text-align: center;
}

.bindingcode-item {
    position: relative;
    padding: 100rpx 20rpx;
}

.bindingcode-input {
    padding: 20rpx 0;
    font-size: 28rpx;
    border-bottom: 4rpx solid #666ee8;
}

.bindingcode-btn {
    margin-top: 60rpx;
    color: #fff !important;
    background-color: #666ee8 !important;
    border-radius: 100rpx;
}

.code {
    position: absolute;
    top: 120rpx;
    right: 30rpx;
    font-size: 24rpx;
    color: #666ee8;
    cursor: pointer;
}

.code.disabled {
    color: #999;
    cursor: not-allowed;
}
</style>